package com.yufu.plugin.sina;

import android.content.Intent;

import androidx.activity.result.ActivityResult;

import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginConfig;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbAuthListener;
import com.sina.weibo.sdk.common.UiError;
import com.sina.weibo.sdk.openapi.IWBAPI;
import com.sina.weibo.sdk.openapi.SdkListener;
import com.sina.weibo.sdk.openapi.WBAPIFactory;

@CapacitorPlugin(name = "Sina", requestCodes = {32973})
public class SinaPlugin extends Plugin {

  private final Sina implementation = new Sina();

  private IWBAPI mWBAPI;
  private static PluginCall currentCall;

  @Override
  public void load() {
    super.load();
    PluginConfig config = getConfig();
    String appKey = config.getString("appKey");
    // String redirectUrl = "https://api.weibo.com/oauth2/default.html";
    String redirectUrl = config.getString("redirectUrl");
    String scope = config.getString("scope");

    AuthInfo authInfo = new AuthInfo(this.getActivity(), appKey, redirectUrl, scope);
    mWBAPI = WBAPIFactory.createWBAPI(this.getContext());
    mWBAPI.registerApp(
      this.getContext(),
      authInfo,
      new SdkListener() {
        @Override
        public void onInitSuccess() {
          System.out.println("onInitSuccess:微博SDK初始化成功");
          // SDK初始化成功回调，成功⼀次后再次初始化将不再有任何回调
        }

        @Override
        public void onInitFailure(Exception e) {
          System.out.println("onInitFailure:微博SDK初始化失败");
          // SDK初始化失败回调
        }
      });
  }

  @PluginMethod
  public void login(PluginCall call) {
    currentCall = call;
    String type = call.getString("type");
    if (type == null) {
      type = "";
    }

    switch (type) {
      case "client":
        this.startClientAuth(call);
        break;
      case "web":
        this.startWebAuth();
        break;
      default:
        this.startAuth();
        break;
    }
  }

  @Override
  protected void handleOnActivityResult(int requestCode, int resultCode, Intent data) {
    super.handleOnActivityResult(requestCode, resultCode, data);
    mWBAPI.authorizeCallback(this.getActivity(), requestCode, resultCode, data);
  }

  /**
   * 授权操作
   */
  private void startAuth() {
    // auth
    mWBAPI.authorize(this.getActivity(), authListener);
  }

  /**
   * 指定通过客户端授权操作
   */
  private void startClientAuth(PluginCall call) {
    mWBAPI.authorizeClient(this.getActivity(), authListener);
  }

  /**
   * 指定通过⽹⻚（H5）授权操作
   */
  private void startWebAuth() {
    mWBAPI.authorizeWeb(this.getActivity(), authListener);
  }

  WbAuthListener authListener = new WbAuthListener() {
    @Override
    public void onComplete(Oauth2AccessToken token) {
      if (token.isSessionValid()) {
        JSObject ret = new JSObject();
        ret.put("token", token.getAccessToken());
        currentCall.resolve(ret);
        return;
      }
      currentCall.reject("授权失败");
    }

    @Override
    public void onError(UiError error) {
      currentCall.reject(error.errorMessage, error.errorCode + "");
    }

    @Override
    public void onCancel() {
      currentCall.reject("微博授权取消");
    }
  };
}
